package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

import com.badibadi.activity.UpPicturesActivity;
import com.badibadi.adapter.Club_Poly_Adapter;
import com.badibadi.adapter.MyPolyAdapter;
import com.badibadi.fragment.MyPolyFragment.SetMyPolyAdapter;
import com.badibadi.infos.Club_Photo_Model;
import com.badibadi.infos.Photo;
import com.badibadi.infos.PhotoModel;
import com.badibadi.infos.Results;
import com.badibadi.interfaces.PolyInterface;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.miloisbadboy.view.PullToRefreshView;
import com.miloisbadboy.view.PullToRefreshView.OnFooterRefreshListener;
import com.miloisbadboy.view.PullToRefreshView.OnHeaderRefreshListener;
//UpPicturesActivity
public class SeeClubPolyFragment extends BaseFragment implements
		OnHeaderRefreshListener, OnFooterRefreshListener {
	static SeeClubPolyFragment seeClubPolyFragment;
	private GridView mGridView;
	private Club_Poly_Adapter myAdapter;
	private List<Photo> photoModels;
	// 收数据的
	private Club_Photo_Model club_Photo_Model;
	// 是否加入 （0，no 1是）
	private String isJoin;
	// 是否是管理员 （0bushi ,1是）
	private String isAdmin;
	/**
	 * 是否需要申请表
	 */
	private String is_apply;
	
	// 是否已经设置过适配器
	private boolean isSetAdapter = false;
	private PolyInterface polyInterface;
	/**
	 * 俱乐部id
	 */
	private String cid = "11";
	/**
	 * 测试用户ID 1：管理员，2：该俱乐部会员 3：未加入该俱乐部用户
	 */
	private String c_uid = "1";

	private int page = 1;
	private int pageNum = 6;
	// private XGridView gv;
	private PullToRefreshView mPullToRefreshView;
	/**
	 * 显示什么
	 */
	private int type = -1;// 0足迹，1梦想 2收藏 -1 全部
	// 版型 有三种 默认0 1参考 ， 2四个格子
	private String Version = "0";
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(), getResources()
							.getString(R.string.l_net_error));
					mPullToRefreshView.onFooterRefreshComplete();
					mPullToRefreshView.onHeaderRefreshComplete();
					if (mPullToRefreshView.getVisibility() == 0
							&& photoModels.isEmpty()) {
						mPullToRefreshView.setVisibility(View.GONE);
					}
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}

				break;
			case 2:
				Utils.ExitPrgress(getActivity());
				mPullToRefreshView.onFooterRefreshComplete();
				mPullToRefreshView.onHeaderRefreshComplete();
				if (club_Photo_Model.getPhoto() != null) {
					photoModels.addAll(club_Photo_Model.getPhoto());
				} else {
					try {
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.l_xa10));
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				// initFragment();
				try {
					if (isSetAdapter == false) {
						isJoin = club_Photo_Model.getIsJoin();
						isAdmin = club_Photo_Model.getIsAdmin();
						setMyAdapter();
						isSetAdapter = true;
					} else {
						myAdapter.notifyDataSetChanged();
					}
					if (mPullToRefreshView.getVisibility() == 8
							&& !photoModels.isEmpty()) {
						mPullToRefreshView.setVisibility(View.VISIBLE);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

				// xListView1.requestLayout();
				// x1Adapter.notifyDataSetChanged();
				break;
			case 3:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(), getResources()
							.getString(R.string.l_xa10));
					mPullToRefreshView.onFooterRefreshComplete();
					mPullToRefreshView.onHeaderRefreshComplete();
					if (mPullToRefreshView.getVisibility() == 0
							&& photoModels.isEmpty()) {
						mPullToRefreshView.setVisibility(View.GONE);
					}
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
				break;
			case 4:
				Utils.ExitPrgress(getActivity());
				try {
					// Utils.showMessage(MyPoly1Activity.this,
					// results2.getRetmsg());
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// uid = getArguments().getString("uid", "26");
		// fid = getArguments().getString("fid", "-1");
		c_uid = Utils.getUid(getActivity());
		cid = getArguments().getString("cid");
		is_apply=getArguments().getString("is_apply");
		photoModels = new ArrayList<Photo>();
	}

	/**
	 * 设置适配器
	 * 
	 * @param view
	 */
	private void setMyAdapter() {
		myAdapter = new Club_Poly_Adapter(getActivity(), photoModels, isJoin,
				isAdmin,is_apply);
		mGridView.setAdapter(myAdapter);
	}

	/**
	 * 查看俱乐部相册浏览列表--POST
	 * 
	 * @param $cid
	 *            //俱乐部id----11
	 * @param $uid
	 *            ;//查看者的用户id-----测试用户ID 1：管理员，2：该俱乐部会员 3：未加入该俱乐部用户
	 * @param $page
	 *            ;//第几页
	 * @param $pageNum
	 *            ;//每页显示条数
	 */
	protected void clubPhoto(final String cid, final String c_uid,
			final int page, final int pageNum) {
		// TODO Auto-generated method stub
		// Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("cid", cid);
				map.put("uid", c_uid);
				map.put("page", "" + page);
				map.put("pageNum", "" + pageNum);
				String invite_content = Utils.sendRequest(map,
						Constants.BadiUrl_1 + "photo/clubPhoto");
				//    
				if (invite_content != null) {
					Results results = Utils.checkResult_NNN(getActivity(),
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
						try {
							club_Photo_Model = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), Club_Photo_Model.class);
							//    
							mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						mHandler.sendEmptyMessage(3);
					}
				} else {
					mHandler.sendEmptyMessage(1);
				}
			}
		});
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.x_gridview, null);
		mGridView = (GridView) view.findViewById(R.id.xgridView11);
		mPullToRefreshView = (PullToRefreshView) view
				.findViewById(R.id.main_pull_refresh_view_club);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(getActivity(),
						UpPicturesActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra("photoid", photoModels.get(arg2).getId());
				intent.putExtra("photo_name", photoModels.get(arg2).getName());
				intent.putExtra("type_upimg", "2");
				intent.putExtra("showType", "img");
				intent.putExtra("isJoin", isJoin);
				intent.putExtra("is_apply", is_apply);
				intent.putExtra("cid", cid);
				getActivity().startActivity(intent);
			}
		});
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		// clubPhoto(cid, c_uid, page, pageNum);
		return view;
	}
	
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		photoModels.clear();
		page=0;
		clubPhoto(cid, c_uid, ++page, pageNum);
		super.onStart();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub

		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	public static SeeClubPolyFragment getInstance() {
		if (seeClubPolyFragment == null) {
			return new SeeClubPolyFragment();
		}
		return seeClubPolyFragment;
	}

	// public void setInterNewClistener(PolyInterface interface1)
	// {
	// polyInterface=interface1;
	// }

	// public void setPolyAdapter(SetMyPolyAdapter mypolyadapter) {
	// mypolyadapter.setPolyAdapter(myAdapter, mGridView, photoModels);
	// }

	public interface SetMyPolyAdapter {
		void setPolyAdapter(MyPolyAdapter adapter, GridView mGridView,
				List<PhotoModel> list);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		// TODO Auto-generated method stub
		clubPhoto(cid, c_uid, ++page, pageNum);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		// TODO Auto-generated method stub
		photoModels.clear();
		page=0;
		clubPhoto(cid, c_uid, ++page, pageNum);
	}

}
